import 'dart:async';

import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_constraint_box_widget/common_constraint_max_width_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_name_and_nick_widget.dart';
import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/company/company_detail/bean/company_detail_response_bean.dart';
import 'package:e_reception_flutter/ui/company/company_detail/widgets/company_attention_widget/special_attention_call_back.dart';
import 'package:e_reception_flutter/ui/company/company_detail/widgets/company_attention_widget/special_attention_staff_list_view.dart';
import 'package:e_reception_flutter/ui/company/company_detail_by_type_list/bean/company_detail_by_type_list_response_bean.dart';
import 'package:e_reception_flutter/ui/create_user/user_selectsort/update_task_view_model.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_global_func.dart';
import 'package:e_reception_flutter/utils/vg_label_utils.dart';
import 'package:e_reception_flutter/utils/vg_string_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:e_reception_flutter/vg_widgets/vg_pull_to_refresh_widget/vg_pull_to_refresh_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_pull_to_refresh_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';

import '../../../../app_main.dart';

/// 特别关心-列表项 //--CompanyDetailByTypeListItemWidget
///

class SpecialAttentionStaffListWidget extends StatefulWidget {
  final GroupPersonCntBean tabsList;
  final MultiHandleCallBack multiHandleCallBack;
  final List<CompanyDetailByTypeListItemBean> listItemSelect;
  final TabController tabController;

  SpecialAttentionStaffListWidget(
      {Key key,
      this.tabsList,
      this.multiHandleCallBack,
      this.listItemSelect,
      this.tabController})
      : super(key: key);

  @override
  _SpecialAttentionStaffListWidgetState createState() =>
      _SpecialAttentionStaffListWidgetState();
}

class _SpecialAttentionStaffListWidgetState extends BasePagerState<
    CompanyDetailByTypeListItemBean,
    SpecialAttentionStaffListWidget> with AutomaticKeepAliveClientMixin {
  SpecialAttentionStaffListViewModel _viewModel;
  StreamSubscription eventStreamSubscription;
  bool selectAll = false; //是否全部选中
  int selectIndividual = 1; //是否选中 0全部显示1全不显示 2个别显示
  CompanyDetailByTypeListResponseBean SpecialConcernList = new CompanyDetailByTypeListResponseBean();

  List<CompanyDetailByTypeListItemBean> listAllItemSelect;

  // StreamSubscription updateunallocatedSubscription;
  @override
  void initState() {
    super.initState();
    //观察者模式,监听接口是否使用
    eventStreamSubscription =
        VgEventBus.global.on<MultiDelegeRefreshEvent>().listen((event) {
          selectAll = false;
      setState(() {});
    });
    _viewModel?.topInfoValueNotifier?.addListener(() {
      SpecialConcernList = _viewModel?.topInfoValueNotifier?.value;
      setState(() { });
    });
    _viewModel = SpecialAttentionStaffListViewModel(this, widget?.tabsList);
    _viewModel?.refresh();
  }


  @override
  void dispose() {
    // updateunallocatedSubscription.cancel();
    eventStreamSubscription.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
        Container(
          margin: EdgeInsets.only(top: 45),
          child: _toListBean(),
        ),
        _toFunctionBar(),
      ],
    );
  }

  Widget _toListBean() {
    listAllItemSelect = data;
    return VgPullRefreshWidget.bind(
      //与viewmodel合用获取data
      viewModel: _viewModel,
      state: this,
      child: ListView.separated(
          itemCount: data?.length ?? 0,
          padding: const EdgeInsets.all(0),
          physics: BouncingScrollPhysics(),
          keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
          itemBuilder: (BuildContext context, int index) {
            return _toListItemWidget(context, data?.elementAt(index));
          },
          separatorBuilder: (BuildContext context, int index) {
            return SizedBox(
              height: 0,
            );
          }),
    );
  }

  Widget _toFunctionBar() {
    return Positioned(
      top: 0,
      left: 0,
      right: 0,
      child: Container(
        height: 45,
        color: ThemeRepository.getInstance().getCardBgColor_21263C(),
        alignment: Alignment.centerLeft,
        child: GestureDetector(
          behavior: HitTestBehavior.translucent,
          onTap: () {
            selectAll = !selectAll;
            //点击全选，列表设置为true
            if (selectAll) {
              selectIndividual = 0;
              listAllItemSelect?.forEach((element) {
                if(!(element?.isSelect??false)){
                  widget?.multiHandleCallBack(element);
                  element?.isSelect = true;
                  widget?.listItemSelect?.add(element);
                }
                return;
              });
            }
            if (!selectAll) {
              selectIndividual = 1;
              listAllItemSelect?.forEach((element) {
                element?.isSelect = false;
                widget?.multiHandleCallBack(element);
                widget?.listItemSelect.remove(element);
              });
            }
            setState(() {});
          },
          child: Row(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 15),
                child: Image.asset(
                  selectAll
                      ? "images/common_selected_ico.png"
                      : "images/common_unselect_ico.png",
                  height: 20,
                ),
              ),
              Text(
                "全选",
                style: TextStyle(color: Color(0xFFD0E0F7), fontSize: 15),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _toListItemWidget(BuildContext context,
      CompanyDetailByTypeListItemBean companyDetailByTypeListItemBean) {
    return Container(
      height: 64,
      margin: const EdgeInsets.symmetric(horizontal: 15),
      child: GestureDetector(
        behavior: HitTestBehavior.translucent,
          onTap: () {
            companyDetailByTypeListItemBean?.isSelect =
            !(companyDetailByTypeListItemBean?.isSelect ?? false);
            if (companyDetailByTypeListItemBean?.isSelect ?? false) {
              widget?.listItemSelect.add(companyDetailByTypeListItemBean);
              widget?.multiHandleCallBack(companyDetailByTypeListItemBean);

              int i = 0;
              //判断是否对应全选
              widget?.listItemSelect?.forEach((element) {
                if(companyDetailByTypeListItemBean?.groupid == element?.groupid){
                    i++;
                    listAllItemSelect?.length!=i ? selectAll = false :selectAll = true ;
                }
              });
            } else {
              widget?.listItemSelect.remove(companyDetailByTypeListItemBean);
              widget?.multiHandleCallBack(companyDetailByTypeListItemBean);

              int i = 0;
              if(widget?.listItemSelect?.length==0){selectAll=false;}
              //判断是否对应全选
              widget?.listItemSelect?.forEach((element) {
                if(companyDetailByTypeListItemBean?.groupid == element?.groupid){
                  i++;
                  listAllItemSelect?.length!=i ? selectAll = false :selectAll = true ;
                }else selectAll=false;
              });
            }
            setState(() {});
          },
          child: _toMainRowWidget(context, companyDetailByTypeListItemBean)),
    );
  }

  Widget _toMainRowWidget(BuildContext context,
      CompanyDetailByTypeListItemBean companyDetailByTypeListItemBean) {
    return Row(
      children: <Widget>[
        _toImageSelect(companyDetailByTypeListItemBean),
        SizedBox(
          width: 15,
        ),
        ClipRRect(
          borderRadius: BorderRadius.circular(4),
          child: Stack(
            children: <Widget>[
              Container(
                width: 36,
                height: 36,
                child: VgCacheNetWorkImage(
                  showOriginEmptyStr(companyDetailByTypeListItemBean?.putpicurl) ??
                      showOriginEmptyStr(
                          companyDetailByTypeListItemBean?.napicurl ?? "") ??
                      (companyDetailByTypeListItemBean?.pictureUrl ?? ""),
                  fit: BoxFit.cover,
                  imageQualityType: ImageQualityType.middleDown,
                  defaultErrorType: ImageErrorType.head,
                  defaultPlaceType: ImagePlaceType.head,
                ),
              ),
              if(companyDetailByTypeListItemBean?.special??false )
               _specialAttentionImg(),
            ],

          ),
        ),
        SizedBox(
          width: 10,
        ),
        Container(
          height: 36,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Row(
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  (false)
                      ? Text(
                          "未知",
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                              color: ThemeRepository.getInstance()
                                  .getMinorRedColor_F95355(),
                              fontSize: 15,
                              height: 1.2),
                        )
                      : CommonNameAndNickWidget(
                          name:
                              "${companyDetailByTypeListItemBean?.name ?? "-"}",
                          nick:
                              "${companyDetailByTypeListItemBean?.nick ?? ""}",
                        ),
                  VgLabelUtils.getRoleLabel(
                          companyDetailByTypeListItemBean?.roleid ?? "10") ??
                      Container(),
                  _toPhoneWidget(companyDetailByTypeListItemBean),
                ],
              ),
              SizedBox(
                height: 2,
              ),
              //判断如果部门项目城市班级不为空那么就显示出来。否则显示手机号
              if (!VgStringUtils.checkAllEmpty([
                companyDetailByTypeListItemBean?.department?.trim(),
                // companyDetailByTypeListItemBean?.projectname?.trim(),
                // companyDetailByTypeListItemBean?.city?.trim(),
                companyDetailByTypeListItemBean?.classname?.trim(),
                // companyDetailByTypeListItemBean?.coursename?.trim(),
              ]))
                Expanded(
                  child: Builder(builder: (BuildContext context) {
                    return CommonConstraintMaxWidthWidget(
                      maxWidth: ScreenUtils.screenW(context) / 2,
                      child: Text(
                        // (itemBean?.isUnknow() ?? false)
                        //     ? (VgDateTimeUtils.getFormatTimeStr(
                        //             itemBean?.lastPunchTime) ??
                        //         "")
                        //     : (StringUtils.isNotEmpty(itemBean?.phone)
                        //         ? "${itemBean.phone}"
                        //         : "暂无手机号码"),
                        VgStringUtils.getSplitStr([
                          companyDetailByTypeListItemBean?.department?.trim(),
                          // companyDetailByTypeListItemBean?.projectname?.trim(),
                          // companyDetailByTypeListItemBean?.city?.trim(),
                          companyDetailByTypeListItemBean?.classname?.trim(),
                          // companyDetailByTypeListItemBean?.coursename?.trim(),
                        ], symbol: "/"),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                          color: VgColors.INPUT_BG_COLOR,
                          fontSize: 12,
                        ),
                      ),
                    );
                  }),
                ),
            ],
          ),
        ),
      ],
    );
  }

  Widget _specialAttentionImg(){
    return Positioned(
         bottom: 2,
        right: 2,
        child: Image.asset("images/specialAttention.png",width: 10,));
  }

  Widget _toImageSelect(
      CompanyDetailByTypeListItemBean companyDetailByTypeListItemBean) {
    return Container(
        width: 20,
        height: 20,
        child: Image.asset(
            companyDetailByTypeListItemBean?.isSelect ?? false
                ? "images/common_selected_ico.png"
                : "images/common_unselect_ico.png",
            height: 20));
  }

  Widget _toPhoneWidget(
      CompanyDetailByTypeListItemBean companyDetailByTypeListItemBean) {
    return Offstage(
      offstage: companyDetailByTypeListItemBean?.phone == null ||
          companyDetailByTypeListItemBean?.phone.isEmpty,
      // offstage: false,
      child: GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () {
          _call(companyDetailByTypeListItemBean?.phone);
        },
        child: Container(
          width: 16,
          height: 16,
          margin: const EdgeInsets.only(left: 4, right: 10),
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(2),
              color: ThemeRepository.getInstance()
                  .getPrimaryColor_1890FF()
                  .withOpacity(0.1)),
          child: Icon(
            Icons.phone,
            size: 10,
            color: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
          ),
        ),
      ),
    );
  }

  void _call(String phone) async {
    if (StringUtils.isEmpty(phone)) {
      return;
    }
    if (phone.length != DEFAULT_PHONE_LENGTH_LIMIT) {
      VgToastUtils.toast(AppMain.context, "手机号不正确");
      return;
    }
    if (await canLaunch("tel:" + phone)) {
      await launch("tel:" + phone);
    } else {
      throw 'Could not launch $phone';
    }
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}
